﻿using Microsoft.AspNetCore.Cors.Infrastructure;

namespace JLMiddlewares
{
    /// <summary>
    /// 给返回数据增加允许跨域访问的头信息中间件
    /// </summary>
    public class CorsMiddleware
    {
        private readonly RequestDelegate next;

        public CorsMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
            {
                if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
                {
                    context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
                    context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH");
                    context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
                    context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
                    //允许前端跨域使用的Head节点名称
                    context.Response.Headers.Add("Access-Control-Expose-Headers", string.Join(",", new string[] { "TokenID" }));
                    //前端缓存依据，Origin 为根据网址缓存，网址变化则缓存失效
                    context.Response.Headers.Add("Vary", "Origin");

                    context.Response.Headers.Add("Server", "JL");

                    if (context.Request.Method.Equals("OPTIONS"))
                    {
                        context.Response.StatusCode = StatusCodes.Status200OK;
                        return;
                    }
                }
            }
            await next(context);
        }
    }
}
